package com.zzw.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zzw.entity.CurrentUser;
import com.zzw.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Project: warehouse
 * @Description: token工具类
 * @Author: zzw
 */
@Component
public class TokenUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //注入配置文件中的warehouse-expire-time属性 -- token的过期时间
    @Value("${warehouse-expire-time}")
    private int expireTime;

    //token中存放用户id对应的名字
    private static final String CLAIM_NAME_USERID = "CLAIM_NAME_USERID";
    //token中存放用户名对应的名字
    private static final String CLAIM_NAME_USERCODE = "CLAIM_NAME_USERCODE";
    //token中存放用户真实姓名对应的名字
    private static final String CLAIM_NAME_USERNAME = "CLAIM_NAME_USERNAME";

    private String sign(CurrentUser currentUser, String securityKey) {
        return JWT.create()
                .withClaim(CLAIM_NAME_USERID, currentUser.getUserId())
                .withClaim(CLAIM_NAME_USERCODE, currentUser.getUserCode())
                .withClaim(CLAIM_NAME_USERNAME, currentUser.getUserName())
                .withIssuedAt(new Date())//发行时间
                .withExpiresAt(new Date(System.currentTimeMillis() + expireTime * 1000L))//有效时间
                .sign(Algorithm.HMAC256(securityKey));
    }

    // 将当前用户信息以用户密码为密钥生成token的方法
    public String loginSign(CurrentUser currentUser, String password) {
        // 生成token
        String token = sign(currentUser, password);
        // 将token保存到redis中，并设置token在redis中的过期时间
        stringRedisTemplate.opsForValue().set(token, token, expireTime * 2L, TimeUnit.SECONDS);
        return token;
    }

    // 从客户端归还的token中获取用户信息的方法
    public CurrentUser getCurrentUser(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("令牌为空，请登录！");
        }
        //对token进行解码，并获取解码后的token
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = JWT.decode(token);
        } catch (JWTDecodeException e) {
            throw new BusinessException("令牌格式错误，请登录！");
        }
        // 从解码的token中获取用户信息并封装
        int userId = decodedJWT.getClaim(CLAIM_NAME_USERID).asInt();//用户账号id
        String userCode = decodedJWT.getClaim(CLAIM_NAME_USERCODE).asString();
        String userName = decodedJWT.getClaim(CLAIM_NAME_USERNAME).asString();
        if (StringUtils.isEmpty(userCode) || StringUtils.isEmpty(userName)) {
            throw new BusinessException("令牌缺失用户信息，请登录！");
        }
        return new CurrentUser(userId, userCode, userName);
    }
}
